<template>
  <div class="layout">
    <el-container class="container">
      <el-header class="myHeader">
        <div style="display: flex; justify-content: space-between; align-items: center">
          <img class="logo pointer" src="/kyland.png" @click="cilckIndexLogo">
          <div style="display: flex;align-items: center">
            <el-select v-model="language" style="width: 100px;" popper-class="selectFrom" @change="changeLanguage"
                       placeholder="选择语言">
              <el-option value="en" label="英文"/>
              <el-option value="cn" label="中文"/>
            </el-select>
            <span style="width: 20px;height: 20px;margin-left: 10px">
            <img v-if="state.showMenu" alt="退出登录" src="/quit.png" style="width: 100%;height: 100%;" class="pointer"
                 @click="quitLogin">
            </span>
          </div>
        </div>
      </el-header>
      <el-container class="content">
        <el-aside v-if="state.showMenu" class="aside">
          <Menu/>
        </el-aside>
        <el-main style="padding: 0;">
          <div class="main" :class="{'main-noMenu': !state.showMenu}">
            <router-view/>
          </div>
          <Footer v-if="state.showMenu"/>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import Menu from '@/components/Menu.vue'
import {reactive, ref, onBeforeMount} from 'vue'
import {useRouter} from 'vue-router'
import Footer from '@/components/Footer.vue'
import {reqHeartBeat, reqLogout} from '@/api/index'
import {localGet, localRemove} from '@/utils'
import {useI18n} from 'vue-i18n'
import {ElMessage} from "element-plus";
import permission from "@/utils/permission";

const language = ref()
const {locale, t} = useI18n()
const router = useRouter()

const state = reactive({
  showMenu: false,
  defaultOpen: ['1'],
  currentPath: '/',
})
onBeforeMount(() => {
  language.value = localGet('lang')
  console.log('app初始化', language.value)
})

function changeLanguage(val) {
  window.location.reload()
  locale.value = val
  localStorage.setItem('lang', val)
}

function cilckIndexLogo() {
  router.push('/')
}

async function quitLogin() {
  // debugger
  await reqLogout()
  timer && clearInterval(timer)
  localRemove('token')
  await router.replace('/login')
  window.location.reload()
}

function heartBeat() {
  reqHeartBeat().then((res) => {
    console.log('心跳结果', res.state)
    if (res.state == 'offline') {
      console.log('心跳结果为offline自动退出登录')
      quitLogin()
    }
  })
}

let timer = null
let isAdd = false
let isAddAdmin = false
/**
 * 全局前置路由守卫
 */
router.beforeEach((to, from, next) => {
  console.log('进入路由守卫,',to,from)
  if (to.path == '/login') {
    // 如果路径是 /login 则正常执行
    console.log('路由是logni，正常跳转')
    state.showMenu = false
    next()
  } else {

    // 如果不是 /login，判断是否有 token
    if (!localGet('token')) {
      // 如果没有，则跳至登录页面
      next({path: '/login', replace: true})
      state.showMenu = false
      ElMessage.error('登录状态已过期,请重新登陆!')
    } else {
      const user = localGet('token')
      const level = user.level
      heartBeat()
      timer && clearInterval(timer)
      timer = setInterval(heartBeat, 5000)
      // 有token就是已登录,继续执行,显示菜单
      state.showMenu = true
      if (permission.admin.includes(level) && !isAddAdmin) {
        isAddAdmin = true
        console.log('当前权限是管理员，添加用户管理路由', user)
        router.addRoute({
          path: '/user-manage',
          name: 'user-manage',
          meta: {
            title: '用户管理'
          },
          component: () => import(/* webpackChunkName: "Log" */ './views/users/UserManage.vue')
        })
        next({...to, replace: true})
      } else if (permission.adminAndWrite.includes(level) && !isAdd) {
        isAdd = true
        console.log('当前权限是读写或者管理员，添加系统路由', user)
        // 动态添加的路由数组
        const routes = [
          {
            path: '/backup',
            name: 'backup',
            meta: {
              title: '备份/恢复'
            },
            component: () => import(/* webpackChunkName: "Log" */ './views/system/Backup.vue')
          },
          {
            path: '/upgrade',
            name: 'upgrade',
            meta: {
              title: '升级'
            },
            component: () => import(/* webpackChunkName: "Log" */ './views/system/Upgrade.vue')
          },
          {
            path: '/system-reset',
            name: 'system-reset',
            meta: {
              title: '系统重置'
            },
            component: () => import(/* webpackChunkName: "Log" */ './views/system/Reset.vue')
          },
          {
            path: '/reboot',
            name: 'reboot',
            meta: {
              title: '重启'
            },
            component: () => import(/* webpackChunkName: "Log" */ './views/system/Reboot.vue')
          }
        ]
        routes.forEach((route) => {
          router.addRoute(route)
        })
        next({...to, replace: true})
      } else {
        next()
      }
    }
  }
  state.currentPath = to.path
  document.title = to.meta.title
})
</script>

<style lang="scss" scoped>

.selectFrom {
  //color: #fff;
  //border: 1px solid #176168 !important;
  //
  //
  //.el-select-dropdown__list {
  //  text-align: right;
  //  background: #17616800 !important;
  //}
  //
  //.el-select-dropdown__item {
  //  color: #fff;
  //  background: #17616800 !important;
  //}
  //
  //.el-select-dropdown__item.hover,
  //.el-select-dropdown__item:hover {
  //  background: #1b7f5d !important;
  //}
}

.logo {
  cursor: pointer;
  width: 142px;
  height: 50px;
}

.layout {
  min-height: 100vh;
  width: 100%;
  overflow: hidden;
  background-color: #ffffff;
}

.container {
  height: 100vh;
  background-color: #F5F5F5;
}

.myHeader {
  background-color: #2D2C33;
  font-size: 20px;
  max-height: 50px;
  color: #e6a23c;
}

.aside {
  height: calc(100vh - 50px);
  width: 220px !important;
  padding-left: 0;
  padding-right: 0;
  margin-right: 20px;
  margin-bottom: 0;
  margin-left: -5px;
  background-color: #fff;
  z-index: 10;
}

.head {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
}

.head > div {
  display: flex;
  align-items: center;
}

.head img {
  width: 50px;
  height: 50px;
  margin-right: 10px;
}

.head span {
  font-size: 20px;
  color: #ffffff;
}

.line {
  border-top: 1px solid hsla(0, 0%, 100%, .05);
  border-bottom: 1px solid rgba(0, 0, 0, .2);
}

.content {
  height: calc(100vh - 50px);
}

.main {
  min-height: calc(100% - 55px);
  width: 100%;
  //overflow: auto;
  //border-radius: 8px 8px 8px 8px;
  /*padding: 10px;*/
}
.main-noMenu{
  height: 100%;
}
</style>

<style>
body {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.el-menu {
  border-right: none !important;
}

.el-submenu {
  border-top: 1px solid hsla(0, 0%, 100%, .05);
  border-bottom: 1px solid rgba(0, 0, 0, .2);
}

.el-submenu:first-child {
  border-top: none;
}

.el-submenu [class^="el-icon-"] {
  vertical-align: -1px !important;
}

a {
  color: #409eff;
  text-decoration: none;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}

.el-popper__arrow {
  display: none;
}

.el-menu-item.is {
  background-color: #C29B74 !important;
  border-radius: 8px 8px 8px 8px;
  color: #fff;
}

/*菜单被选中*/
.el-menu-item.is-active {
  background-color: #C29B74 !important;
  border-radius: 8px 8px 8px 8px;
  color: #fff;
}

.el-menu-item.is-active > span {
  color: #fff !important;
}

.el-form-item__label {
  font-size: 14px !important;
  font-family: "Microsoft YaHei";
  font-weight: 400 !important;
  color: #161940 !important;
}
</style>